package zzs.generalframework.config.core.database.mysql.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import javax.sql.DataSource;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

/**
 * @title
 * @description
 * @project zzs-config
 * @package zzs.generalframework.config.core.database.mysql.jpa
 * @author zzs
 * @date 2018年2月5日
 * @version 1.0
 */
@Configuration
public class DatabaseConnection
{

	@Autowired
	@Qualifier("springDataSource")
	DataSource dataSource;

	@Bean("mysqlLocalContainerEntityManagerFactoryBean")
	public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean()
	{
		LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

		localContainerEntityManagerFactoryBean.setDataSource(dataSource);
		localContainerEntityManagerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter());
		localContainerEntityManagerFactoryBean.setJpaDialect(hibernateJpaDialect());
		localContainerEntityManagerFactoryBean.setPersistenceProvider(hibernatePersistenceProvider());
		localContainerEntityManagerFactoryBean.setPersistenceXmlLocation("classpath:config/database/persistence-entity.xml");
		localContainerEntityManagerFactoryBean.setPersistenceUnitName("zzs-entity");

		return localContainerEntityManagerFactoryBean;

	}

	@Bean("entityManagerFactory")
	public javax.persistence.EntityManagerFactory entityManagerFactory()
	{
		return localContainerEntityManagerFactoryBean().getObject();
	}

	private JpaVendorAdapter hibernateJpaVendorAdapter()
	{
		HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
		jpaVendorAdapter.setDatabase(Database.MYSQL);
		jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
		jpaVendorAdapter.setGenerateDdl(false);
		return jpaVendorAdapter;
	}

	private JpaDialect hibernateJpaDialect()
	{
		return new HibernateJpaDialect();
	}

	private PersistenceProvider hibernatePersistenceProvider()
	{
		return new HibernatePersistenceProvider();
	}

}
